package com.google.code.spidertr;
import java.util.List;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LinkFinder {
	/**
	 * TODO:
	 */
	private String baseURI;
	/**
	 * TODO:
	 */
	private String content;
	/**
	 * TODO:
	 */
	private Pattern patternLink;
	/**
	 * TODO:
	 */
	private Pattern patternHtmltag;

	public LinkFinder(String baseURI, String content) {
		this.baseURI = baseURI;
		this.content = content;
		initiatePatterns();

	}

	/**
	 * The method initiates patterns...
	 */
	private void initiatePatterns() {
		this.patternLink = Pattern.compile("href=\"[^>]*\">");
		this.patternHtmltag = Pattern
				.compile("<a\\b[^>]*href=\"[^>]*>(.*?)</a>");
	}

	/**
	 * Return list of Links in the Content.
	 * 
	 * @return {@link List} of links.
	 */
	public List<String> findLinks() {

		Matcher tagmatch = patternHtmltag.matcher(content);
		List<String> links = new Vector<String>();
		while (tagmatch.find()) {
			Matcher matcher = patternLink.matcher(tagmatch.group());
			matcher.find();

			String link = new LinkBuilder(matcher.group(), baseURI)
					.getLink();
			if (link != null)
				links.add(link);
		}
		return links;
	}

}